'use strict';

const { Controller } = require('egg');
const { Op } = require('sequelize');
const serviceName = 'wx'
const axios = require('axios'); // 导入 Axios 模块，用于发起 HTTP 请求
const sha1 = require('js-sha1') // 引入加密方法

let wxConfig = {
    appid: "wx657a882f4bdfb19c", // 公众号
    secret: '0df8bbfa4f960cebdc1884613019c668', // 小程序密钥
}

// 获取 Ticket 通过 Access Token
async function getJsapiTicket(access_token) {
    // JS-SDK使用权限签名算法
    // 官方说明地址：https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62
    const url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket`;

    const response = await axios({
        method: "get",
        url,
        params: {
            type: 'jsapi',
            access_token,
        },
    });


    if (response?.data.errcode) {
        throw new Error(JSON.stringify(response.data))
    }

    // response.data：
    // {
    //   "errcode":0,
    //   "errmsg":"ok",
    //   "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
    //   "expires_in":7200
    // }

    return response.data;
}

// 获取 Access token
async function getAccessToken() {
    // 获取 Access token
    // 官方说明地址：https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
    const url = `https://api.weixin.qq.com/cgi-bin/token`;

    const response = await axios({
        method: "get",
        url,
        params: {
            grant_type: 'client_credential',
            appid: wxConfig.appid,
            secret: wxConfig.secret,
        },
    });

    if (response?.data.errcode) {
        if (response?.data.errcode === 40013) {
            throw new Error('AppID无效错误')
        } else {
            throw new Error(JSON.stringify(response.data))
        }
    }

    // response.data： {"access_token":"ACCESS_TOKEN","expires_in":7200}

    return response.data;
}

// 生成时间戳
const generateTimestamp = () => Date.parse(new Date()) / 1000

// 生成随机字符串
const generateNoncestr = () => {
    const n = 17
    let nonceStr = ''
    const str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    const len = str.length
    for (let i = 0; i < n; i += 1) {
        const rand = Math.floor(Math.random() * len)
        nonceStr += str.charAt(rand)
    }
    return nonceStr
}

// 生成签名
const generateSignature = (jsapi_ticket, noncestr, timestamp, url) => {
    // 介绍 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#62
    const obj = {
        jsapi_ticket,// 有效的jsapi_ticket
        noncestr,//随机字符串
        timestamp,//时间戳
        url // 当前网页的URL
    }
    let str = ''
    Object.keys(obj).forEach((k) => {
        str += `&${k}=${obj[k]}`
    })
    return sha1(str.slice(1))
}
class RouterController extends Controller {

    async wxConfig() {
        // 获取query
        const { query } = this.ctx
// 1、接收前端传来的 url
        const url = 'http://vote.diandian.work'
// 2、判断是否传入了 url
        if (!url) throw new Error('url 不能为空！1111')
// 3、获取 access_token
        const access_tokenInfo = await getAccessToken()
// 4、用 access_token 获取 jsapi_ticket
        const jsapi_ticketInfo = await getJsapiTicket(access_tokenInfo.access_token)
// 5、生成时间戳
        const timestamp = generateTimestamp()
// 6、生成随机字符串
        const nonceStr = generateNoncestr()
// 7、生成签名
        const signature = generateSignature(jsapi_ticketInfo.ticket, nonceStr, timestamp,url)
// 8、响应数据给前端
        this.ctx.success({
            appId: wxConfig.appid,
            timestamp,
            nonceStr,
            signature
        })
    }

}

module.exports = RouterController;
